package com.forum.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.forum.enums.myOps1;
import com.forum.pojo.ForumArticle;
import com.forum.pojo.ForumArticleAttachment;
import com.forum.pojo.vo.ArticleModify;
import com.forum.pojo.vo.ForumArticleDetailVo;
import com.forum.result.Result;
import com.forum.service.ForumArticleAttachmentService;
import com.forum.service.ForumArticleService;
import com.forum.service.LikeRecordService;
import com.forum.utils.JwtHelper;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/forum")
public class ForumController {
    @Autowired
    private ForumArticleService forumArticleService;
    @Autowired
    private LikeRecordService likeRecordService;
    @Autowired
    private ForumArticleAttachmentService forumArticleAttachmentService;
    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation(value = "通过条件查询话题广场帖子")
    @GetMapping("/find0BoardEssay")
    public Result<List<ArticleModify>> find0BoardEssay(String theme, @RequestParam String findType) {
        if (theme != "" && theme != null) {
            theme = '%' + theme + '%';
        }
        List<ArticleModify> forumArticles = forumArticleService.find0BoardEssay(theme, findType);
            return Result.ok(forumArticles);
    }

    @ApiOperation(value = "通过条件查询教师资源分享帖子")
    @GetMapping("/find1BoardEssay")
    public Result<Page> find1BoardEssay(@RequestParam Long pageNum, @RequestParam Long pageSize, String theme, @RequestParam Integer findType) {
        Page forumArticles = forumArticleService.find1BoardEssay(pageNum, pageSize, theme, findType);
        if (forumArticles != null) {
            return Result.ok(forumArticles);
        }
        return null;
    }

    /**
     * 根据artickeid获取具体帖子
     *
     * @param articleId
     * @return
     */
    @RequestMapping(path = "/getArticleDetail", method = RequestMethod.GET)
    public Result getArticleDetail(@RequestParam String articleId,@RequestParam Integer forLike) {
        String[] attachmentUrls = new String[0];
        ForumArticle article = forumArticleService.selectByArticleId(articleId);
        System.out.println(article.getAttachmentType());
        if (1 == article.getAttachmentType()) {
            ForumArticleAttachment forumArticleAttachment = forumArticleAttachmentService.selectByArticleId(articleId);
            if(forumArticleAttachment!=null){
                String filePath = forumArticleAttachment.getFilePath();
                System.out.println(filePath);
                if (filePath!=null)
                    attachmentUrls = filePath.split(",");
            }
        }
        if(forLike==0)
            forumArticleService.readArticle(articleId);

        Long userId = article.getUserId();
        String avatar = forumArticleService.selectAvatarByUserId(userId);
        Integer identity=forumArticleService.selectIdentityByUserId(userId);
        ForumArticleDetailVo articleDetailVo = new ForumArticleDetailVo(article, attachmentUrls, avatar,identity);
        return Result.ok(articleDetailVo);
    }


    @ApiOperation(value = "添加帖子")
    @Transactional(rollbackFor = {Exception.class}, readOnly = false)
    @RequestMapping(method = RequestMethod.POST, path = "/add")
    public Result addArticle(HttpServletRequest request,
                             String attachmentUrls,
                             @RequestParam Integer pBoardId,
                             @RequestParam String title,
                             @RequestParam String content,
                             String summary,
                             @RequestParam String tag,
                             @RequestParam Integer questionType,
                             String answer,
                             @RequestParam Integer attachmentType,
                             @DateTimeFormat(
                                     pattern = "yyyy-MM-dd HH:mm:ss"
                             )
                             Date deadLine) {
        String token = request.getHeader("token");
        String value = (String) redisTemplate.opsForValue().get(token);
        Long userId = JwtHelper.getUserId(value);
        ForumArticle forumArticle = new ForumArticle();
        forumArticle.setpBoardId(pBoardId);
        if (pBoardId == 0) {
            forumArticle.setpBoardName("话题广场");
        } else if (pBoardId == 1) {
            forumArticle.setpBoardName("教师资源分享");
        } else forumArticle.setpBoardName("新生可了解");

        forumArticle.setTitle(title);
        forumArticle.setContent(content);
        forumArticle.setSummary(summary);
        forumArticle.setUserId(userId);
        forumArticle.setStatus(0);
        forumArticle.setStar(0);
        //通过userId寻找nickname
        String nickName = forumArticleService.findNickNameByUserId(userId);
        System.out.println(nickName);
        forumArticle.setNickName(nickName);
        forumArticle.setTag(tag);
        forumArticle.setQuestionType(questionType);
        if (answer != "" && answer != null)
            forumArticle.setAnswer(answer);
        else forumArticle.setAnswer("");
        forumArticle.setAttachmentType(attachmentType);
        forumArticle.setDeadline(deadLine);
        System.out.println(forumArticle);
        ForumArticleAttachment forumArticleAttachment = new ForumArticleAttachment();

        String[] _attachmentUrls=attachmentUrls.split(",");

        this.forumArticleService.postArticle(forumArticle, forumArticleAttachment, _attachmentUrls);
        return Result.ok(forumArticle.getArticleId());
    }

    /**
     * 文章点赞
     *
     * @param articleId
     * @return
     */
    @RequestMapping(path = "/doLike", method = RequestMethod.POST)
    public Result doLike(HttpServletRequest request, @RequestParam String articleId) {
        //获取用户id和昵称
        String token = request.getHeader("token");
        String value = (String) redisTemplate.opsForValue().get(token);
        Long userId = JwtHelper.getUserId(value);
        likeRecordService.doLike(articleId, userId, myOps1.ARTICLE_LIKE);
        return Result.ok();
    }
    @ApiOperation("管理员删除文章")

    @DeleteMapping("/deleteByArticleId")
    public Result deleteByArticleId(@RequestParam String articleId) {

        if (forumArticleService.deleteByArticleId(articleId)) {
            return Result.ok();
        } else {
            return Result.build(320, "删除失败");
        }
    }
    @ApiOperation("管理员加精文章")
    @PostMapping("/starArticle")
    public Result starArticle(@RequestParam String articleId,@RequestParam Integer type){
        int result=forumArticleService.setStar(articleId,type);
        if(result==0){
            return Result.build(321,"修改失败");
        }else{
            return Result.ok();
        }
    }
    @ApiOperation("管理员置顶帖子")
    @PostMapping("/topArticle")
    public Result topArticle(@RequestParam String articleId,@RequestParam Integer type){
        int result=forumArticleService.setTop(articleId,type);
        if(result==0){
            return Result.build(321,"修改失败");
        }else{
            return Result.ok();
        }
    }
}
